<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>订单管理</el-breadcrumb-item>
      <el-breadcrumb-item>销售单列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getOrdersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getOrdersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-button type="primary" @click="exportExcel"
          >点击导出表格数据</el-button
        >
      </el-row>
      <!-- 表格数据 -->
      <el-table
        :data="
          orderList.slice(
            (queryInfo.pageNum - 1) * queryInfo.pageSize,
            queryInfo.pageNum * queryInfo.pageSize
          )
        "
        border
        stripe
        id="out-table"
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          label="订单编号"
          prop="order_id"
          width="160px"
        ></el-table-column>
        <el-table-column
          label="下单客户"
          prop="order_customer"
          width="90px"
        ></el-table-column>
        <el-table-column
          label="供应商"
          prop="order_provider"
          width="120px"
        ></el-table-column>
        <el-table-column
          label="产品"
          prop="order_product"
          width="100px"
        ></el-table-column>
        <el-table-column
          label="数量"
          prop="order_number"
          width="70px"
        ></el-table-column>
        <el-table-column
          label="订单价格"
          prop="order_price"
          width="80px"
        ></el-table-column>
        <el-table-column label="订单盈亏" width="80px"
          ><template slot-scope="scope">
            <el-tag
              type="success"
              v-if="
                calculate(
                  scope.row.order_price,
                  scope.row.order_number,
                  scope.row.order_product
                ) > 0
              "
            >
              {{
                calculate(
                  scope.row.order_price,
                  scope.row.order_number,
                  scope.row.order_product
                )
              }}</el-tag
            >
            <el-tag type="danger" v-else>
              {{
                calculate(
                  scope.row.order_price,
                  scope.row.order_number,
                  scope.row.order_product
                )
              }}</el-tag
            >
          </template></el-table-column
        >
        <el-table-column
          label="下单管理员"
          prop="order_admin1"
          width="100px"
        ></el-table-column>
        <el-table-column
          label="结单管理员"
          prop="order_admin2"
          width="100px"
        ></el-table-column>
        <el-table-column label="下单时间" width="180px">
          <template slot-scope="scope">{{
            scope.row.order_time1 | dataFormat
          }}</template>
        </el-table-column>
        <el-table-column label="订单完成时间" width="180px">
          <template slot-scope="scope">{{
            scope.row.order_time2 | dataFormat
          }}</template>
        </el-table-column>
        <el-table-column label="订单备注" prop="order_remark"></el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
// 引入导出Excel表格依赖
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  data() {
    return {
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 10
      },
      // 订单列表
      orderList: [],
      // 订单总数
      total: 0
    }
  },
  created() {
    this.getProductList()
    this.getOrdersList()
  },
  methods: {
    // 根据分页获取对应的订单列表
    async getOrdersList() {
      const { data: res } = await this.$http.get('allOrder', {
        params: this.queryInfo
      })
      if (res.numbers < 1) {
        return this.$message.error('获取订单列表失败！')
      }
      console.log(res)
      //赋值前清除，不然会有数据重复
      this.orderList = []
      //临时存储
      var arr = res.data
      //order_is_sale字段为true，则为销售单
      for (let item of arr) {
        if (item.order_is_sale == true) {
          this.orderList.push(item)
        }
      }
      this.total = this.orderList.length
    },
    async getProductList() {
      const { data: res } = await this.$http.get('allProducts')
      this.productList = res.data
      console.log(this.productList)
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getOrdersList()
    },
    handleCurrentChange(newSize) {
      this.queryInfo.pageNum = newSize
      this.getOrdersList()
    },
    //计算盈亏
    calculate(price, num, product) {
      //首先从商品库获取商品单价
      //盈亏=订单金额-（商品数量*商品单价）
      //商品单价
      var productPrice = 0
      for (let item of this.productList) {
        if (item.productName == product) {
          productPrice = item.price
          break
        }
      }
      return price - num * productPrice
    },
    exportExcel() {
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: 'application/octet-stream' }),
          //设置导出文件名称
          '导出数据文件.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    }
  }
}
</script>

<style lang="less" scoped>
.el-button--success {
  margin-left: 30px;
}
.el-button--danger {
  margin-left: 30px;
}
</style>
